package cn.ming.wfchat.app.main;

import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;

import com.liaoinstan.springview.container.DefaultHeader;
import com.liaoinstan.springview.widget.SpringView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.PopupMenu;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import cn.ming.wfchat.R;
import cn.ming.wfchat.app.AppService;
import cn.ming.wfchat.app.me.activity.model.DynamicsCommentsBean;
import cn.ming.wfchat.app.moment.CommentFragment;
import cn.ming.wfchat.app.moment.third.Constants;
import cn.ming.wfchat.app.moment.third.adapters.FriendCircleAdapter;
import cn.ming.wfchat.app.moment.third.beans.CommentBean;
import cn.ming.wfchat.app.moment.third.beans.DynamicsBean;
import cn.ming.wfchat.app.moment.third.beans.Feed;
import cn.ming.wfchat.app.moment.third.beans.FriendCircleBean;
import cn.ming.wfchat.app.moment.third.beans.PraiseBean;
import cn.ming.wfchat.app.moment.third.interfaces.OnCommentItemClickListener;
import cn.ming.wfchat.app.moment.third.interfaces.OnCommentLike;
import cn.ming.wfchat.app.moment.third.interfaces.OnCommentReply;
import cn.ming.wfchat.app.moment.third.interfaces.OnFeedUserClickListener;
import cn.ming.wfchat.app.moment.third.interfaces.OnPraiseOrCommentClickListener;
import cn.ming.wfchat.app.moment.third.interfaces.OnTopTheMenu;
import cn.ming.wfchat.app.moment.third.others.FriendsCircleAdapterDivideLine;
import cn.ming.wfchat.app.moment.third.utils.Utils;
import cn.ming.wfchat.app.moment.third.widgets.CommentOrPraisePopupWindow;
import cn.ming.wfchat.app.utils.SoftKeyBoardListener;
import cn.ming.wfchat.kit.net.base.StatusResult;
import cn.wildfirechat.model.UserInfo;
import cn.wildfirechat.remote.ChatManager;

public class DiscoveryFragment extends Fragment implements OnCommentItemClickListener, OnFeedUserClickListener, OnPraiseOrCommentClickListener,
        OnCommentLike, OnCommentReply, OnTopTheMenu {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.springView)
    SpringView springView;
    private int page = 1;
    private FriendCircleAdapter mFriendCircleAdapter;
    private CommentOrPraisePopupWindow mCommentOrPraisePopupWindow;
    protected CommentFragment commentFragment;
    private List<FriendCircleBean> friendCircleBeans;
    protected LinearLayoutManager layoutManager;
    private boolean isLoadingOldFeed;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.main_fragment_discovery, container, false);
        ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        initView();
        updateMomentBadgeView();
        return view;
    }

    protected void initView() {

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }

            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                if (!recyclerView.canScrollVertically(1)) {
                    int lastVisibleItem = layoutManager.findLastCompletelyVisibleItemPosition();
                    if (!isLoadingOldFeed && lastVisibleItem > mFriendCircleAdapter.getItemCount() - 3) {
                        page++;
                        updateMomentBadgeView();
                    }
                }
            }
        });
        layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new FriendsCircleAdapterDivideLine());

        mFriendCircleAdapter = new FriendCircleAdapter(getActivity(), recyclerView);
        mFriendCircleAdapter.setOnCommentItemClickListener(this);
        mFriendCircleAdapter.setOnFeedUserClickListener(this);
        mFriendCircleAdapter.setOnCommentLike(this);
        mFriendCircleAdapter.setOnCommentReply(this);
        mFriendCircleAdapter.setOnTopTheMenu(this::TopTheMenu);
        mFriendCircleAdapter.setOnPraiseOrCommentClickListener(this::toggleCommentOrPraisePopupWindow);
        friendCircleBeans = new ArrayList<>();
        mFriendCircleAdapter.setFriendCircleBeans(friendCircleBeans);
        recyclerView.setAdapter(mFriendCircleAdapter);
        springView.setHeader(new DefaultHeader(getActivity()));
        springView.setListener(new SpringView.OnFreshListener() {
            public void onRefresh() {
                page = 1;
                updateMomentBadgeView();
            }

            @Override
            public void onLoadmore() {

            }
        });
        SoftKeyBoardListener.setListener(getActivity(), new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {

            }

            @Override
            public void keyBoardHide(int height) {
                hideCommentFragment();
            }
        });

    }

    private void updateMomentBadgeView() {
        mFriendCircleAdapter.showLoadingOldFeedItem();
        isLoadingOldFeed = true;
        AppService.Instance().findDynamics(page, new AppService.FindDynamicCallback() {
            @Override
            public void onUiSuccess(Feed assetsBean) {
                springView.onFinishFreshAndLoad();
                if (assetsBean.getDynamicsBeans() == null || assetsBean.getDynamicsBeans().isEmpty() || assetsBean.getDynamicsBeans().size() < 1) {
                    mFriendCircleAdapter.showVisibleScopeItem();
                    return;
                }
                mFriendCircleAdapter.hideLoadingOldFeedItem();
                if (page == 1) {
                    friendCircleBeans = feedsToFriendCircleBeans(assetsBean.getDynamicsBeans());
                } else {
                    friendCircleBeans.addAll(feedsToFriendCircleBeans(assetsBean.getDynamicsBeans()));
                }
                mFriendCircleAdapter.setFriendCircleBeans(friendCircleBeans);
                isLoadingOldFeed = false;
            }

            @Override
            public void onUiFailure(int code, String msg) {
                mFriendCircleAdapter.hideLoadingOldFeedItem();
                ChatManager.showToast(msg);
                isLoadingOldFeed = false;
            }
        });
    }

    public void toggleCommentOrPraisePopupWindow(View anchorView, FriendCircleBean friendCircleBean, int position) {
        if (mCommentOrPraisePopupWindow == null) {
            List<PraiseBean> praiseBeans = friendCircleBean.getPraiseBeans();
            boolean like = false;
            if (praiseBeans != null) {
                for (PraiseBean praiseBean : praiseBeans) {
                    if (praiseBean.getPraiseUserId().equals(ChatManager.Instance().getUserId())) {
                        like = true;
                        break;
                    }
                }
            }
            mCommentOrPraisePopupWindow = new CommentOrPraisePopupWindow(getActivity());
        }
        mCommentOrPraisePopupWindow
                .setOnPraiseOrCommentClickListener(this)
                .setCurrentPosition(position);
        if (mCommentOrPraisePopupWindow.isShowing()) {
            mCommentOrPraisePopupWindow.dismiss();
        } else {
            hideCommentFragment();
            mCommentOrPraisePopupWindow.showPopupWindow(anchorView);
        }
    }

    private void hideCommentFragment() {
        if (commentFragment == null) {
            return;
        }
        commentFragment.hideKeyboard();
        getChildFragmentManager().beginTransaction().remove(commentFragment).commit();
        commentFragment = null;
    }

    /**
     * @param commentId
     * @param hash
     */
    private void showCommentFragment(String commentId, String hash) {
        if (commentFragment != null) {
            return;
        }
        commentFragment = new CommentFragment();
        Bundle bundle = new Bundle();
        bundle.putString("commentId", commentId);
        bundle.putString("hash", hash);
        commentFragment.setArguments(bundle);
        getChildFragmentManager().beginTransaction().
                replace(R.id.commentLayoutContainer, commentFragment, "comment")
                .show(commentFragment)
                .commit();
    }


    /**
     * 点击评论
     *
     * @param commentItemView
     * @param feedPosition
     * @param commentPosition
     */
    @Override
    public void onCommentItemClick(View commentItemView, int feedPosition, int commentPosition) {
        if (commentFragment != null) {
            hideCommentFragment();
            return;
        }
        List<FriendCircleBean> friendCircleBeans = mFriendCircleAdapter.getmFriendCircleBeans();
        FriendCircleBean friendCircleBean = friendCircleBeans.get(feedPosition);
        List<CommentBean> commentBeans = friendCircleBean.getCommentBeans();
        CommentBean commentBean = commentBeans.get(commentPosition);

        if (commentBean.getChildUserId().equals(ChatManager.Instance().getUserId())) {
            PopupMenu popup = new PopupMenu(getActivity(), commentItemView);
            popup.getMenuInflater().inflate(R.menu.comment_item_delete_popup_menu, popup.getMenu());
            popup.setOnMenuItemClickListener(item -> {
                if (item.getItemId() == R.id.delete) {
                    deleteComment(feedPosition, commentPosition);
                }

                return true;
            });
            popup.show();
        } else {
            int[] location = new int[2];
            commentItemView.getLocationInWindow(location);
            int bottom = location[1] + commentItemView.getHeight();
            int scrollBy = getCommentPanelTop() - bottom;
            recyclerView.scrollBy(0, -scrollBy);
            showCommentFragment(commentBean.getId() + "", friendCircleBean.getHash());
        }
    }

    /**
     * 点赞
     *
     * @param userId
     */
    @Override
    public void onFeedUserClick(String userId) {

    }

    @Override
    public void onPraiseClick(int position) {
        List<FriendCircleBean> friendCircleBeans = mFriendCircleAdapter.getmFriendCircleBeans();
        FriendCircleBean friendCircleBean = friendCircleBeans.get(position);
        List<PraiseBean> praiseBeans = friendCircleBean.getPraiseBeans();
        PraiseBean praiseBean = new PraiseBean();
        UserInfo userInfo = ChatManager.Instance().getUserInfo(ChatManager.Instance().getUserId(), false);
        praiseBean.setPraiseUserId(userInfo.uid);
        praiseBean.setPraiseUserName(userInfo.displayName);
        List<PraiseBean> beans = new ArrayList<>();
        AppService.Instance().dynamicsLikes(friendCircleBean.getHash(), new AppService.DynamicsLikesCallback() {
            @Override
            public void onUiSuccess(StatusResult assetsBean) {
                if (praiseBeans == null) {
                    // praiseBean.setId(id);
                    beans.add(praiseBean);
                    friendCircleBean.setPraiseBeans(beans);
                } else {
                    if (praiseBeans.contains(praiseBean)) {
                        praiseBeans.remove(praiseBean);
                        friendCircleBean.setPraiseBeans(praiseBeans);
                    } else {
                        // praiseBean.setId(id);
                        praiseBeans.add(praiseBean);
                        friendCircleBean.setPraiseBeans(praiseBeans);
                    }
                }
                mFriendCircleAdapter.notifyItemChanged(position + mFriendCircleAdapter.headerCount(), Collections.singleton("star"));
            }

            @Override
            public void onUiFailure(int code, String msg) {
                ChatManager.showToast(msg);

            }
        });


    }

    @Override
    public void onCommentClick(View view, int position) {
        if (commentFragment != null) {
            hideCommentFragment();
            return;
        }
        View itemView = layoutManager.findViewByPosition(position + mFriendCircleAdapter.headerCount());
        int scrollBy = getCommentPanelTop() - itemView.getBottom();
        recyclerView.scrollBy(0, -scrollBy);
        List<FriendCircleBean> friendCircleBeans = mFriendCircleAdapter.getmFriendCircleBeans();
        FriendCircleBean friendCircleBean = friendCircleBeans.get(position);
        showCommentFragment(null, friendCircleBean.getHash());
    }


    protected List<FriendCircleBean> feedsToFriendCircleBeans(List<DynamicsBean> dynamicsBeans) {
        List<FriendCircleBean> friendCircleBeans = new ArrayList<>();
        if (dynamicsBeans != null) {
            for (DynamicsBean dynamicsBean : dynamicsBeans) {
                FriendCircleBean friendCircleBean = FriendCircleBean.fromFeed(getActivity(), dynamicsBean);
                friendCircleBeans.add(friendCircleBean);
            }
        }
        return friendCircleBeans;
    }

    private int getCommentPanelTop() {
        int commentPanelTop = PreferenceManager.getDefaultSharedPreferences(getActivity())
                .getInt("commentPanelTop", 0);
        if (commentPanelTop > 0) {
            return commentPanelTop;
        }

        WindowManager manager = getActivity().getWindowManager();
        DisplayMetrics outMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(outMetrics);
        int height = outMetrics.heightPixels;
        return height - (getKeyboardPortraitHeight() + Utils.dp2px(40));
    }

    private int getKeyboardPortraitHeight() {
        int defaultCustomKeyboardSize = getResources().getDimensionPixelSize(R.dimen.default_custom_keyboard_size);
        int minCustomKeyboardSize = getResources().getDimensionPixelSize(R.dimen.min_custom_keyboard_size);
        int keyboardHeight = PreferenceManager.getDefaultSharedPreferences(getActivity())
                .getInt("keyboard_height_portrait", defaultCustomKeyboardSize);
        return Math.max(keyboardHeight, minCustomKeyboardSize);
    }

    public void commentFeed(String hash, String comment) {

        int position = mFriendCircleAdapter.getFeedPosition(hash);
        AppService.Instance().dynamicsReply(null, hash + "", comment, new AppService.DynamicsReplyCallback() {
            @Override
            public void onUiSuccess(DynamicsCommentsBean assetsBean) {
                FriendCircleBean friendCircleBean = mFriendCircleAdapter.getFriendCircleBean(hash);
                CommentBean commentBean = new CommentBean();
                commentBean.setCommentContent(comment);
                commentBean.setId(assetsBean.getId());
                UserInfo userInfo = ChatManager.Instance().getUserInfo(ChatManager.Instance().getUserId(), false);
                commentBean.setChildUserId(userInfo.uid);
                commentBean.setChildUserName(userInfo.displayName);
                commentBean.setCommentType(Constants.CommentType.COMMENT_TYPE_SINGLE);
                List<CommentBean> commentBeans = friendCircleBean.getCommentBeans();
                if (commentBeans == null) {
                    commentBeans = new ArrayList<>();
                }
                //commentBean.setId(id);
                commentBeans.add(commentBean);
                friendCircleBean.setCommentBeans(commentBeans);
                mFriendCircleAdapter.notifyItemChanged(position + mFriendCircleAdapter.headerCount(), Collections.singleton("comment"));
                hideCommentFragment();
            }

            @Override
            public void onUiFailure(int code, String msg) {
                ChatManager.showToast(msg);
            }
        });

    }

    public void replyComment(String hash, String commentId, String comment) {
        int position = mFriendCircleAdapter.getFeedPosition(hash);
        CommentBean parentCommentBean = mFriendCircleAdapter.getCommentBean(hash, commentId);
        AppService.Instance().dynamicsReply(commentId + "", hash, comment, new AppService.DynamicsReplyCallback() {
            @Override
            public void onUiSuccess(DynamicsCommentsBean assetsBean) {
                FriendCircleBean friendCircleBean = mFriendCircleAdapter.getFriendCircleBean(hash);
                CommentBean commentBean = new CommentBean();
                commentBean.setCommentContent(comment);
                commentBean.setId(assetsBean.getId());
                UserInfo userInfo = ChatManager.Instance().getUserInfo(ChatManager.Instance().getUserId(), false);
                commentBean.setChildUserId(userInfo.uid);
                commentBean.setChildUserName(userInfo.displayName);
                commentBean.setParentUserId(parentCommentBean.getChildUserId());
                commentBean.setParentUserName(parentCommentBean.getChildUserName());
                commentBean.setCommentType(Constants.CommentType.COMMENT_TYPE_REPLY);
                List<CommentBean> commentBeans = friendCircleBean.getCommentBeans();
                if (commentBeans == null) {
                    commentBeans = new ArrayList<>();
                }
                //commentBean.setId(0);
                commentBeans.add(commentBean);
                friendCircleBean.setCommentBeans(commentBeans);
                mFriendCircleAdapter.notifyItemChanged(position + mFriendCircleAdapter.headerCount(), Collections.singleton("comment"));
                hideCommentFragment();
            }

            @Override
            public void onUiFailure(int code, String msg) {

            }
        });


    }

    /**
     * 删除评论
     *
     * @param feedPosition
     * @param dynamicsCommentId
     */
    void deleteComment(int feedPosition, int dynamicsCommentId) {
        List<FriendCircleBean> friendCircleBeans = mFriendCircleAdapter.getmFriendCircleBeans();
        FriendCircleBean friendCircleBean = friendCircleBeans.get(feedPosition);
        List<CommentBean> commentBeans = friendCircleBean.getCommentBeans();
        CommentBean commentBean = commentBeans.get(dynamicsCommentId);
        AppService.Instance().removeDynamicsComment(commentBean.getId() + "", new AppService.DynamicsLikesCallback() {
            @Override
            public void onUiSuccess(StatusResult assetsBean) {
                commentBeans.remove(commentBean);
                friendCircleBean.setCommentBeans(commentBeans);
                mFriendCircleAdapter.notifyItemChanged(feedPosition + mFriendCircleAdapter.headerCount(), Collections.singleton("comment"));
            }

            @Override
            public void onUiFailure(int code, String msg) {
                ChatManager.showToast(msg);
            }
        });
    }

    /**
     * 设置私有或者公开
     *
     * @param hash
     * @param friendCircleBean
     * @param position
     */
    void updateDynamicsPrivate(String hash, FriendCircleBean friendCircleBean, int position) {
        AppService.Instance().updateDynamicsPrivate(hash, new AppService.DynamicsLikesCallback() {
            @Override
            public void onUiSuccess(StatusResult assetsBean) {
                if (friendCircleBean.isPrivateOwner()) {
                    mFriendCircleAdapter.getmFriendCircleBeans().get(position).setPrivateOwner(false);
                } else {
                    mFriendCircleAdapter.getmFriendCircleBeans().get(position).setPrivateOwner(true);
                }
                mFriendCircleAdapter.notifyItemChanged(position + mFriendCircleAdapter.headerCount(), Collections.singleton("comment"));
            }

            @Override
            public void onUiFailure(int code, String msg) {
                ChatManager.showToast(msg);
            }
        });

    }

    /**
     * 删除朋友圈
     */
    void removeDynamics(String hash, FriendCircleBean friendCircleBean, int position) {
        List<FriendCircleBean> friendCircleBeans = mFriendCircleAdapter.getmFriendCircleBeans();
        AppService.Instance().removeDynamics(hash, new AppService.DynamicsLikesCallback() {
            @Override
            public void onUiSuccess(StatusResult assetsBean) {
                friendCircleBeans.remove(friendCircleBean);
                mFriendCircleAdapter.setFriendCircleBeans(friendCircleBeans);
              //  mFriendCircleAdapter.notifyItemRemoved(position + mFriendCircleAdapter.headerCount());
            }

            @Override
            public void onUiFailure(int code, String msg) {
                ChatManager.showToast(msg);
            }
        });
    }

    @Subscribe
    public void onEventReceive(EventBusBean event) {
        if (EventConstant.UPDATEMOMENTS.equals(event.getEventName())) {
            page = 1;
            updateMomentBadgeView();
        }
    }

    @Override
    public void CommentLike(View anchorView, FriendCircleBean friendCircleBean, int position) {
        onPraiseClick(position);
    }

    @Override
    public void CommentReply(View anchorView, FriendCircleBean friendCircleBean, int position) {
        onCommentClick(anchorView, position);
    }

    @Override
    public void TopTheMenu(View anchorView, FriendCircleBean friendCircleBean, int position) {
        PopupMenu popup = new PopupMenu(getActivity(), anchorView);

        popup.getMenuInflater().inflate(R.menu.comment_item_top_popup_menu, popup.getMenu());
        MenuItem menuItem = popup.getMenu().getItem(0);
        if (friendCircleBean.isPrivateOwner()) {
            menuItem.setTitle("公开");
        } else {
            menuItem.setTitle("设为私有");
        }
        popup.setOnMenuItemClickListener(item -> {
            if (item.getItemId() == R.id.delete) {
                removeDynamics(friendCircleBean.getHash(), friendCircleBean, position);
            } else if (item.getItemId() == R.id.set_private) {

                updateDynamicsPrivate(friendCircleBean.getHash(), friendCircleBean, position);
            }

            return true;
        });
        popup.show();
    }

}
